<template>
  <div class="LoginMain">
    <el-row>
      <!-- 这里xs的作用是只要屏幕的宽度小于768px的时候,就只会显示右边的内容-->
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          class="login_form"
          :model="userinfo"
          ref="loginForms"
          :rules="rules"
        >
          <h1>hello</h1>
          <h2>欢迎来到王世彪管理后台项目</h2>
          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              v-model="userinfo.username"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              v-model="userinfo.password"
              :prefix-icon="Lock"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              class="login_btn"
              @click="loginaction(loginForms)"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts"  setup>
import { User, Lock } from "@element-plus/icons-vue";
import { onMounted, reactive, ref ,watch} from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElNotification } from "element-plus";
// 在这边引入小仓库
import loginStore from "@/store/modules/login";
// 引入时间函数
import { getTime } from "@/utils/time.ts";
import type { FormInstance, FormRules } from "element-plus";
import { userLoginwsb } from "@/api/user/index.ts";
import { asyncRoute, } from '@/router/routes.ts'

// import { userLoginwsb } from "@/api/index.ts";
//获取路由器
let $router = useRouter();
// 获取路由信息
let $route = useRoute();
let loginInfo = loginStore();
const { userLogin } = loginInfo;
let loading = ref<Boolean>(false);
let userinfo = reactive({ username: "admin", password: "111111" });
let loginForms = ref<FormInstance>();
// console.log(loginForms.value.validate(), "wulalal");
//自定义校验规则函数
const validatorUserName = (rule: any, value: any, callback: any) => {
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  if (value.length >= 5) {
    callback();
  } else {
    callback(new Error("账号长度至少五位"));
  }
};

const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.length >= 6) {
    callback();
  } else {
    callback(new Error("密码长度至少六位"));
  }
};

//定义表单校验需要配置对象
const rules = {
  //规则对象属性:s
  //required,代表这个字段务必要校验的
  //min:文本长度至少多少位
  //max:文本长度最多多少位
  //message:错误的提示信息
  //trigger:触发校验表单的时机 change->文本发生变化触发校验,blur:失去焦点的时候触发校验规则
  username: [
    // { required: true, min: 6, max: 10, message: '账号长度至少六位', trigger: 'change' }
    { trigger: "change", validator: validatorUserName },
  ],
  password: [
    // { required: true, min: 6, max: 15, message: '密码长度至少6位', trigger: 'change' }
    { trigger: "change", validator: validatorPassword },
  ],
};

let loginaction = async (formEl: FormInstance | undefined) => {
  console.log(formEl, "表单验证");
  //下面的这个写法是官网的写法但是因为async和await的原因会报错
  // if (!formEl) return;
  // formEl.validate((valid) => {
  //   if (valid) {
  //     console.log("submit");
  //   } else {
  //     console.log("error submit");
  //   }
  // });
  //这是老师的写法
  //保证全部表单相校验通过再发请求
  await loginForms.value.validate();
  loading.value = true;
  try {
    await userLogin(userinfo);
   
    // 登录成功提示信息
    ElNotification({
      type: "success",
      message: "欢迎回来",
      title: `HI,${getTime()}好`,
    });
    loading.value = false;
     //判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
    let redirect: any = $route.query.redirect;
    console.log(redirect,asyncRotes.value, 'redirect');

 
     
   
    console.log(result, '见证奇迹的时刻');
    if (result) {
      $router.push({ path: redirect || "/" });
      
    } else {
     
      $router.push({ path: "/404" });
    }
    //页面刷新(这里防止异步路由加载权限出现问题，暂时先这么做) 
    // window.location.reload();
  } catch (error) {
    //登录失败的提示信息
    loading.value = false;

    ElNotification({
      type: "error",
      message: (error as Error).message,
    });
  }

  // userTestLogin({
  //   loginname: "admin",
  //   password: "123456",
  // }).then((res) => {
  //   console.log("测试接口返回的数据", res);
  // });
};

watch(() => loginInfo.token, async(newvalue,oldvalue) => {
  console.log(newvalue, oldvalue, 'token的新旧值');
    await loginInfo.userInfo();
     
})
let asyncRotes = ref()
let asyncRotesString = localStorage.getItem('userAllRoutes')
    if (asyncRotesString) {
      asyncRotes.value = JSON.parse(asyncRotesString);
      // 使用asyncRotes变量...
      console.log(asyncRotes, 'asyncRotes');
      //TODO
      //将异步路由添加到路由器当中
  
} else {
  // 处理'userAllRoutes'键不存在的情况...
}
const result = containsStringInNestedArray(asyncRotes.value, $route.query.redirect as String ) 
function containsStringInNestedArray(arr:any, searchStr:String) {
  return arr.some(item => {
    // 检查当前对象的所有属性值
    for (const key in item) {
      const value = item[key];
      
      // 如果是字符串且匹配
      if (typeof value === 'string' && value === searchStr) {
        return true;
      }
      
      // 如果是children数组且递归找到匹配
      if (key === 'children' && Array.isArray(value) && containsStringInNestedArray(value, searchStr)) {
        return true;
      }
    }
    return false;
  });
}







</script>

<style scoped lang="scss" >
.LoginMain {
  width: 100%;
  height: 100vh;
  background: url("@/assets/images/background.jpg") no-repeat;
  background-size: cover;
  .login_form {
    position: relative;
    width: 80%;
    top: 30vh;
    background: url("@/assets/images/login_form.png") no-repeat;
    background-size: cover;
    padding: 50px;
    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      font-size: 20px;
      color: white;
      margin: 20px 0px;
    }
    .el-form-item {
      margin-bottom: 22px; /* Element Plus 默认值为 22px */
    }
    .login_btn {
      width: 100%;
    }
  }
}
</style>